<template>
  <el-card>
    <el-form label-width="100px">
      <el-form-item label="角色名:">
        <span>{{ route.query.roleName }}</span>
      </el-form-item>
      <el-form-item label="角色权限:">
        <el-tree
          class="role-tree"
          ref="treeRef"
          :data="permissionList"
          show-checkbox
          default-expand-all
          node-key="id"
          :props="{
            children: 'children',
            label: 'name',
          }"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="router.go(-1)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "roleAuth",
};
</script>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getRolePermissionApi,
  assignRolePermissionApi,
} from "@/api/acl/permission";
import type { PermissionList } from "@/api/acl/model/permissionModel";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();

// 全部权限列表
const permissionList = ref<PermissionList>([]);

const treeRef = ref();

// 获取选中的菜单id
function getSelectPermission(permissionList: PermissionList) {
  let selectPermissionList: string[] = [];

  permissionList.forEach((permission) => {
    if (permission.select) {
      selectPermissionList.push(permission.id);
    }

    const childrenSelectPermissionList = getSelectPermission(
      permission.children
    );

    selectPermissionList = [
      ...selectPermissionList,
      ...childrenSelectPermissionList,
    ];
  });

  return selectPermissionList;
}

onMounted(async () => {
  const result = await getRolePermissionApi(route.query.id as string);
  permissionList.value = result.children;
  // 遍历所有数据，查找select：true的菜单
  const checkedPermissionList = getSelectPermission(result.children);
  // console.log(checkedPermissionList);
  treeRef.value.setCheckedKeys(checkedPermissionList);
});

const submitForm = async () => {
  // 选中的所有菜单id
  const checkedKeys = treeRef.value.getCheckedKeys();
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  await assignRolePermissionApi(route.query.id as string, [
    ...checkedKeys,
    ...halfCheckedKeys,
  ]);
  ElMessage.success("分配角色权限成功");
  router.push({
    name: "Role",
  });
};
</script>

<style scoped>
.role-tree {
  min-width: 120px;
}
</style>
